package com.vegetable.modules.service.finance;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

/**
 * ECharts图表生成服务
 * 使用ECharts生成图表图片
 *
 * @author Qoder
 */
@Service
public class EChartsGenerationService {

    @Value("${chart.service.url:http://localhost:8080/echarts}")
    private String chartServiceUrl;

    /**
     * 生成财务分析图表Base64图片数据
     *
     * @param financialData 财务数据
     * @param chartType 图表类型 (summary, monthly)
     * @return Base64图片数据
     */
    public String generateChartBase64(JSONObject financialData, String chartType) {
        try {
            String option = generateChartOption(financialData, chartType);
            return renderChartToBase64(option);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成图表配置选项
     *
     * @param financialData 财务数据
     * @param chartType 图表类型
     * @return 图表配置选项JSON字符串
     */
    private String generateChartOption(JSONObject financialData, String chartType) {
        if ("summary".equals(chartType)) {
            return generateSummaryChartOption(financialData);
        } else if ("monthly".equals(chartType)) {
            return generateMonthlyChartOption(financialData);
        }
        return "{}";
    }

    /**
     * 生成总体财务情况图表配置
     *
     * @param financialData 财务数据
     * @return 图表配置选项JSON字符串
     */
    private String generateSummaryChartOption(JSONObject financialData) {
        JSONObject totalAnalyse = financialData.getJSONObject("totalAnalyse");
        if (totalAnalyse == null) {
            return "{}";
        }

        StringBuilder option = new StringBuilder();
        option.append("{");
        option.append("  title: { text: '总体财务情况' },");
        option.append("  tooltip: {},");
        option.append("  legend: { data: ['金额'] },");
        option.append("  xAxis: { data: ['销售额', '支出', '欠款', '未回款', '账户余额'] },");
        option.append("  yAxis: {},");
        option.append("  series: [{");
        option.append("    name: '金额',");
        option.append("    type: 'bar',");
        option.append("    data: [");
        option.append(totalAnalyse.get("sales")).append(",");
        option.append(totalAnalyse.get("expenses")).append(",");
        option.append(totalAnalyse.get("debt")).append(",");
        option.append(totalAnalyse.get("noReturn")).append(",");
        option.append(totalAnalyse.get("totalBalance"));
        option.append("] }]");
        option.append("}");

        return option.toString();
    }

    /**
     * 生成月度财务数据图表配置
     *
     * @param financialData 财务数据
     * @return 图表配置选项JSON字符串
     */
    private String generateMonthlyChartOption(JSONObject financialData) {
        List<List> monthData = (List<List>) financialData.get("monthData");
        if (monthData == null || monthData.size() <= 1) {
            return "{}";
        }

        StringBuilder option = new StringBuilder();
        option.append("{");
        option.append("  title: { text: '月度财务趋势' },");
        option.append("  tooltip: { trigger: 'axis' },");
        option.append("  legend: { data: ['销售额', '支出', '收入'] },");
        option.append("  xAxis: { type: 'category', data: [");

        // 添加月份数据
        boolean first = true;
        for (int i = 1; i < monthData.size(); i++) {
            List row = monthData.get(i);
            if (row.size() > 0) {
                if (!first) option.append(",");
                option.append("'").append(row.get(0)).append("'");
                first = false;
            }
        }
        option.append("] },");
        option.append("  yAxis: { type: 'value' },");
        option.append("  series: [");

        // 销售额数据
        option.append("{ name: '销售额', type: 'line', data: [");
        first = true;
        for (int i = 1; i < monthData.size(); i++) {
            List row = monthData.get(i);
            if (row.size() > 1) {
                if (!first) option.append(",");
                option.append(row.get(1));
                first = false;
            }
        }
        option.append("] },");

        // 支出数据
        option.append("{ name: '支出', type: 'line', data: [");
        first = true;
        for (int i = 1; i < monthData.size(); i++) {
            List row = monthData.get(i);
            if (row.size() > 2) {
                if (!first) option.append(",");
                option.append(row.get(2));
                first = false;
            }
        }
        option.append("] },");

        // 收入数据
        option.append("{ name: '收入', type: 'line', data: [");
        first = true;
        for (int i = 1; i < monthData.size(); i++) {
            List row = monthData.get(i);
            if (row.size() > 3) {
                if (!first) option.append(",");
                option.append(row.get(3));
                first = false;
            }
        }
        option.append("] }");

        option.append("] }");

        return option.toString();
    }

    /**
     * 渲染图表到Base64图片数据
     *
     * @param option 图表配置选项
     * @return Base64图片数据
     */
    private String renderChartToBase64(String option) {
        try {
            // 这里应该调用实际的图表渲染服务
            // 例如使用PhantomJS、Puppeteer或专门的图表服务来渲染ECharts图表
            // 为了简化示例，这里返回一个示例Base64图片数据
            
            // 实际项目中应该实现真实的图表渲染逻辑
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过HTTP请求渲染图表
     *
     * @param option 图表配置选项
     * @return Base64图片数据
     */
    private String renderChartViaHttp(String option) {
        try {
            URL url = new URL(chartServiceUrl + "/render");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"option\": " + option + "}";

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}